<template>
  <div>
    <!--查询条件-->
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
        <div>
          <p class="label">{{ $t('ledger.RelocationType') }} </p>
          <div class="ipt">
            <Select v-model="searchParams.ydlx" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="(item, index) of changesList" :value="item.id" :label="item.name" :key="index"></Option>
            </Select>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label">{{ $t('ledger.TransactOutFactory') }}</p>
          <div class="ipt">
            <Select v-model="searchParams.oldBelongCompanyId" filterable clearable
              :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="(item, index) of factoryList" :value="item.id" :label="item.name" :key="index"></Option>
            </Select>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label">{{ $t('ledger.TransactInFactory') }}</p>
          <div class="ipt">
            <Select v-model="searchParams.newBelongCompanyId" filterable clearable
              :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="(item, index) of factoryList" :value="item.id" :label="item.name" :key="index"></Option>
            </Select>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label hide-label">--</p>
          <div class="ipt">
            <Button class="search-btn" type="primary" @click="changeNum()" v-if="checkBtnPermission.deviceSwMoveSpList">
              {{ $t('common.Query') }}
            </Button>
            <Button class="reset-btn" @click="reset()" v-if="checkBtnPermission.deviceSwMoveSpList">
              {{ $t('common.reset') }}
            </Button>
          </div>
        </div>
        </Col>
      </Row>
    </div>

    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <!-- <span  class="creatBtnright" @click="handleOutRecords" v-if="checkBtnPermission.alienStatisticsExport">
            <span><Icon type="ios-cloud-download-outline"/></span>
            <span class="rightbtn">{{$t('common.batchExport')}}</span>
        </span>
       <span  class="creatBtnright" @click="handleAdd">
           <span><Icon type="ios-add-circle-outline"/></span>
           <span class="rightbtn">添加异动</span>
       </span> -->
        <Button @click="getTableColumns(matterColumns)">{{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}</Button>
      </div>
      <div class="tableContent">
        <Table class="resizable-table" border @on-column-width-resize="onColumnWidthResize" style="margin-top: 10px"
          row-key="id" :columns="columnsList" :data="dataSource" @on-selection-change="handleSelectionChange">
          <template slot-scope="{ row }" slot="action">
            <!-- <span class="operationBtn" v-if="checkBtnPermission.dmsMoveApplyAaPass && (row.moveStatus == 1) && row.oldFactory != row.newFactory" @click="handleWrite(row)">录入放行单</span> -->
            <span
              v-if="checkBtnPermission.dmsMoveApplyAddFiles && (row.moveStatus === 1 || (row.oldFactory === row.newFactory && row.moveStatus === 1)) && row.files.length === 0"
              class="operationBtn" @click="handleUpload(row)"><i class="iconfont zy-common-shangchuan"></i>{{
                $t('equipmentscrapped.Upload') }}</span>
            <span class="operationBtn" @click="handleDetail(row)" v-if="checkBtnPermission.deviceSwMoveSpView"><i
                class="iconfont zy-common-chakan"></i>{{ $t('common.Check') }}</span>

            <!-- <span class="operationBtn" v-if="checkBtnPermission.dmsMoveApplyAddFiles && (row.moveStatus == 3)" @click="handleUpload(row, 2)">实物接收单</span> -->
          </template>

          <template slot-scope="{ row }" slot="jjswFileName">
            <span v-for="(item, index) in row.files" :key="index">
              <Tag color="blue" type="border" @click.native="handlePreview(item)">
                {{ item.fileName }}
              </Tag>
            </span>
          </template>

        </Table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" />
        <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
          @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total />
      </div>
    </div>
    <Modal :mask-closable="false" v-model="writeVisible" :title="`${$t('ledger.EnterReleaseDoc')}`">
      <Form class="formList" ref="writeForm" :model="formItem" :label-width="120">
        <FormItem :label="`${$t('ledger.ReleaseNumber')}:`" prop="oaNo">
          <Input v-model="formItem.oaNo" clearable :placeholder="`${$t('common.inputInfo')}`" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleCancel">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="loading" @click="handleOk">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="uploadVisible" :title="`${$t('ledger.uploadFiles')}`"
      class="modal-content-layout">
      <div class="upload-box">
        <span class="upload-box-title">
          {{ $t('ledger.TransferForm') }}
        </span>

        <Upload ref="upload" class="upload-box-upload" :show-upload-list="false"
          :before-upload="(file) => handleBeforeUpload(file, transferList, 1, 'EQUIPMENT_CHANGE_DELIVERY_RECEIPT')"
          type="drag" action="" style="width: 120px">
          <!-- 点击上传 -->
          <Button icon="ios-cloud-upload-outline">{{ $t('common.Upload') }}</Button>
        </Upload>

        <div class="uploadWrapper" v-for="(item, index) in transferList " :key="index">
          <a>{{ item.fileName }}</a>
          <Icon class="item-icon" type="ios-trash-outline" size="20" style="float:right;" @click="delFileList(index, 1)">
          </Icon>
        </div>
      </div>
      <Divider />
      <div class="upload-box">
        <span class="upload-box-title">
          {{ $t('ledger.Releasepermit') }}
        </span>

        <Upload ref="upload" class="upload-box-upload" :show-upload-list="false"
          :before-upload="(file) => handleBeforeUpload(file, passList, 2, 'EQUIPMENT_CHANGE_RELEASE_PERMIT')" type="drag"
          action="" style="width: 120px">
          <!-- 点击上传 -->
          <Button icon="ios-cloud-upload-outline">{{ $t('common.Upload') }}</Button>
        </Upload>

        <div class="uploadWrapper" v-for="(item, index) in passList " :key="index">
          <a>{{ item.fileName }}</a>
          <Icon class="item-icon" type="ios-trash-outline" size="20" style="float:right;" @click="delFileList(index, 2)">
          </Icon>
        </div>
      </div>
      <Divider />
      <div class="upload-box">
        <span class="upload-box-title">
          {{ $t('common.other') }}
        </span>

        <Upload ref="upload" class="upload-box-upload" :show-upload-list="false"
          :before-upload="(file) => handleBeforeUpload(file, otherList, 3, 'EQUIPMENT_CHANGE_OTHERS')" type="drag"
          action="" style="width: 120px">
          <!-- 点击上传 -->
          <Button icon="ios-cloud-upload-outline">{{ $t('common.Upload') }}</Button>
        </Upload>

        <div class="uploadWrapper" v-for="(item, index) in otherList " :key="index">
          <a>{{ item.fileName }}</a>
          <Icon class="item-icon" type="ios-trash-outline" size="20" style="float:right;" @click="delFileList(index, 3)">
          </Icon>
        </div>
      </div>
      <div slot="footer">
        <Button type="default" @click="handleUploadCancel">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="uploadLoading" @click="handleUploadOk">
          {{ $t('maintenance.Confirmed') }}
        </Button>
      </div>
    </Modal>
    <!--新增异动-->
    <!--        <add-changes-modal ref="addChangesModal" :factoryList="factoryList" :orgList="orgList"-->
    <!--                           @handleRefresh="handleRefresh"/>-->
  </div>
</template>

<script>
import fileDownload from 'js-file-download'
// import AddChangesModal from './AddChangesModal.vue'
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "changesList",
  mixins: [toggleTableOperation],
  // components: {
  //     AddChangesModal,
  // },
  data() {
    return {
      total: this.matterTotal,
      pageNum: 1,
      pageSize: 10,
      delLoading: false,
      writeVisible: false,
      uploadVisible: false,
      loading: false,
      uploadLoading: false,
      searchParams: {},
      checkBtnPermission: {},
      transferList: [],
      passList: [],
      otherList: [],
      formItem: {
        oaNo: ''
      },
      fileId: null,
      // validateUploadfunction: {
      //     fileName: [
      //         { required: true, message: '请选择文件', trigger: 'blur' }
      //     ],
      // },
      // validateWritefunction: {
      //     oaNo: [
      //         { required: true, message: '请输入放行单号', trigger: 'blur' }
      //     ],
      // },
      pageSizeOption: [10, 20, 30],
      changesList: [
        { id: 0, name: '全部' },
        { id: 1, name: '转售' },
        { id: 2, name: '调拨' },
        { id: 3, name: '租用' },
        { id: 4, name: '借用' },
        { id: 7, name: '借用归还' },
        { id: 5, name: '仅记录' },
        { id: 6, name: '委外生产借用' }
      ],
      matterColumns: [
        {
          title: `${this.$t('ledger.RelocationStatus')}`,
          key: 'moveStatus',
          align: 'center',
          minWidth: 140,
          render: (h, params) => {
            return h('div', params.row.moveStatus == 1 ? '已提交' : params.row.moveStatus == 2 ? '已完成' : '')
          },
          resizable: true
        },
        {
          title: `${this.$t('ledger.RelocationType')}`,
          key: 'ydlx',
          align: 'center',
          minWidth: 120,
          render: (h, params) => {
            return h('div', params.row.ydlx == 1 ? '转售' : params.row.ydlx == 3 ? '租用' : params.row.ydlx == 4 ? '借用' : params.row.ydlx == 5 ? '仅记录' : params.row.ydlx == 6 ? '委外生产借用' : '借用归还')
          },
          resizable: true
        },
        {
          title: `${this.$t('ledger.SerialNo')}`,
          key: 'applyNo',
          align: 'center',
          minWidth: 200,
          resizable: true
        },
        // {
        //     title: 'OA签核单号',
        //     key: 'oaNo',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '放行单号',
        //     key: 'oaNoCheck',
        //     align: 'center',
        //     minWidth: 120,
        // },
        {
          title: `${this.$t('ledger.AppliedBy')}`,
          key: 'applyUserName',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          title: `${this.$t('ledger.TransactOutFactory')}`,
          key: 'oldBelongCompanyName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          title: `${this.$t('ledger.TransactInFactory')}`,
          key: 'newBelongCompanyName',
          align: 'center',
          minWidth: 140,
          resizable: true
        },
        {
          title: `${this.$t('ledger.attachmentinformation')}`,
          slot: 'jjswFileName',
          align: 'center',
          minWidth: 300,
          resizable: true
        },
        // {
        //     title: '附件信息',
        //     key: 'newBelongCompanyName',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '接收人',
        //     key: 'receiveName',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '发货时间',
        //     key: 'sendTime',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '接收时间',
        //     key: 'receiveTime',
        //     align: 'center',
        //     minWidth: 120
        // },

        // {
        //     title: '调出成本中心',
        //     key: 'moveOutCostCenterName',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '调入成本中心',
        //     key: 'moveInCostCenterName',
        //     align: 'center',
        //     minWidth: 120
        // },
        // {
        //     title: '交接单',
        //     key: 'jjFileName',
        //     align: 'center',
        //     minWidth: 300,
        //     ellipsis: true,
        //     render: (h, params) => {
        //         return h('a',
        //             {
        //                 style: {
        //                     color: 'blue',
        //                     cursor: 'pointer'
        //                 },
        //                 on: {
        //                     click: () => {
        //                         this.downloadFile(params.row.jjFileUrl, params.row.jjFileName)
        //                     }
        //                 }
        //             }, params.row.jjFileName)
        //     }
        // },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          minWidth: 200,
          align: "center",
          fixed: 'right',
        }
      ],
      dataSource: this.matterDataSource,
    }
  },
  props: {
    factoryList: {
      type: Array,
      default: () => []
    },
    orgList: {
      type: Array,
      default: () => []
    },
    matterDataSource: {
      type: Array,
      default: () => []
    },
    matterTotal: {
      type: Number,
      default: () => 10
    }
  },
  watch: {
    matterDataSource(newValue) {
      this.dataSource = newValue
    },
    matterTotal(newValue) {
      this.total = newValue
    },
  },
  created() {
    this.getTableColumnsWidth(this.matterColumns)
    this.searchList()
  },
  mounted() {
    let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))
    for (let item of itemList) {
      if (item.code == "deviceSwMoveSpList") {
        this.checkBtnPermission.deviceSwMoveSpList = true
      }
      if (item.code == "deviceSwMoveSpView") {
        this.checkBtnPermission.deviceSwMoveSpView = true
      }
      if (item.code == "dmsMoveApplyAddFiles") {
        this.checkBtnPermission.dmsMoveApplyAddFiles = true
      }
      // if (item.code == "dmsMoveApplyAaPass") {
      //     this.checkBtnPermission.dmsMoveApplyAaPass = true
      // }
    }
  },
  methods: {
    handleCancel() {
      this.writeVisible = false
      this.$refs.writeForm.resetFields();
    },
    handleSelectionChange() {
    },
    downloadFile(url, fileName) {
      console.log(url)
      window.open(url)
      // fileDownload( url, fileName)
      // 创建隐藏的可下载链接
      // let eleLink = document.createElement('a');
      // eleLink.download = fileName;
      // eleLink.style.display = 'none';
      // // 字符内容转变成blob地址
      // // let blob = new Blob([url]);
      // // eleLink.href = URL.createObjectURL(blob);
      // eleLink.href = url;
      // // 触发点击
      // document.body.appendChild(eleLink);
      // eleLink.click();
      // // 然后移除
      // document.body.removeChild(eleLink);
    },
    handleBeforeUpload(file, data, type, fileDocumentEnumPath) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("dir", 'device')
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config,
      }).then(res => {
        if (res.code == 200) {
          this.$nextTick(() => {
            data.push({
              fileName: res.data.fileName,
              fileUrl: res.data.fileUrl,
              filePath: res.data.filepath,
              attachmentType: type,
              applyMoveId: this.fileId,
              fileDocumentEnumPath: fileDocumentEnumPath,
              suffix: res.data.suffix,
              fileSize: res.data.fileLength,
            })
          })
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
        }
      }).catch(() => {
      });
      return false;
    },
    handleUpload(row) {
      this.transferList = [];
      this.passList = [];
      this.otherList = [];
      this.uploadVisible = true;
      this.fileId = row.id;
    },
    handleWrite(row) {
      // this.writeVisible = true
      this.formItem.id = row.id
      this.handleOk()
    },
    handleOk() {
      let params = {
        id: this.formItem.id,
        // oaNo: this.formItem.oaNo,
      }
      this.$refs.writeForm.validate((valid) => {
        if (valid) {
          this.axios({
            method: 'post',
            url: '/dms/dmsMoveApply/oaPass',
            params: params
          }).then(res => {

            if (res.code === 200) {
              this.$Message.success('上传成功！')
              this.writeVisible = false
              this.loading = false
              this.$refs.writeForm.resetFields();
              this.searchList()
            } else {
              this.loading = false
              this.$refs.writeForm.resetFields();
              this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
            }
          }).finally(() => {

          })
        }
      })
    },
    handleUploadCancel() {
      this.uploadVisible = false
    },
    handleUploadOk() {
      if (this.transferList === [] || this.passList === [] || this.otherList === []) {
        this.$Message.error(({ content: "请至少提交一个", duration: 6, closable: true }))
      }
      let params = {
        files: [...this.transferList, ...this.passList, ...this.otherList]
      }
      this.axios({
        method: 'post',
        url: '/dms/dmsMoveApply/addFiles',
        data: params
      }).then(res => {

        if (res.code === 200) {
          this.$Message.success('上传成功！')
          this.searchList()
          this.uploadVisible = false
        } else {
          this.$Message.error(({ content: res.msg, duration: 6, closable: true }))

        }
      }).finally(() => {
        this.uploadLoading = false
      })
    },
    //导出
    handleOutRecords() {
      let params = {};
      for (let key in this.searchParams) {
        if (key === 'orgId' && this.searchParams['orgId']) {
          const arr = this.searchParams[key]
          const { length, last = length - 1 } = arr
          this.$set(params, key, arr[last])
        } else {
          if (this.searchParams[key]) {
            this.$set(params, key, this.searchParams[key])
          }
        }
      }
      const filName = '异动统计'
      this.axios({
        method: 'get',
        url: '/dms/dmsMoveApply/exportMove',
        responseType: 'blob',
        params
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })
    },
    //文件删除
    delFileList(id, type) {
      if (type == 1) {
        this.transferList = this.transferList.filter((item, index) => index != id)
      } else if (type == 2) {
        this.passList = this.passList.filter((item, index) => index != id)
      } else {
        this.otherList = this.otherList.filter((item, index) => index != id)
      }
    },
    //详情页
    handleDetail(row) {
      // this.$refs.addChangesModal.show('detail', row, true)
      this.$router.push(({
        path: "/devBasic/equipmentsChangesManagement/addAndDetail",
        query: {
          handleType: "detail",
          ...row,
          detail: true
        }
      }))
    },
    handleRefresh() {
      this.searchList()
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    handlePreview(item) {
      if (item) {

        window.open(this.util.filePathToUrl(item.filePath))
      }
    },
    searchList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        if (key === 'orgId' && this.searchParams['orgId']) {
          const arr = this.searchParams[key]
          const { length, last = length - 1 } = arr
          this.$set(params, key, arr[last])
        } else {
          if (this.searchParams[key]) {
            this.$set(params, key, this.searchParams[key])
          }
        }

      }
      this.axios({
        method: 'get',
        url: '/dms/dmsMoveApply/getDeviceSwMoveSpList',
        params: params
      }).then(res => {

        if (res.code === 200) {
          this.dataSource = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
.upload-box {

  .upload-box-title {
    display: inline-block;
    font-size: 14px;
    corlor: #333;
  }

  .upload-box-upload {
    margin-top: 20px;
    width: 120px;
  }
}

.uploadWrapper {
  width: 100%;
  line-height: 48px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
  /*a {*/
  /*    display: inline-block;*/
  /*    width: 100%;*/
  /*    line-height: 48px;*/
  /*    !*&:hover {*!*/
  /*    !*    overflow: visible;*!*/
  /*    !*    -ms-text-overflow: inherit;*!*/
  /*    !*    text-overflow: inherit;*!*/
  /*    !*}*!*/
  /*}*/
}

/deep/ .ivu-upload-drag:hover {
  border: none;
}

/deep/ .ivu-upload-drag {
  border: none;
}
</style>
